// COLMAP - Structure-from-Motion and Multi-View Stereo.
// Copyright (C) 2016  Johannes L. Schoenberger <jsch at inf.ethz.ch>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#ifndef COLMAP_SRC_ESTIMATORS_P2P_H_
#define COLMAP_SRC_ESTIMATORS_P2P_H_

#include <vector>

#include <Eigen/Dense>

#include "util/types.h"
#include "estimators/utils.h"

namespace RVG {

// Analytic solver for the P3P (Perspective-Three-Point) problem.
//
// The algorithm is based on the following paper:
//
//    X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang. Complete Solution
//    Classification for the Perspective-Three-Point Problem.
//    http://www.mmrc.iss.ac.cn/~xgao/paper/ieee.pdf
class P2PEstimator {
 public:
  // The 2D image feature observations.
  typedef Eigen::Vector2d X_t;
  // The observed 3D features in the world frame.
  typedef Eigen::Vector3d Y_t;
  // The transformation from the world to the camera frame.
  typedef Eigen::Matrix3x4d M_t;

  // The minimum number of samples needed to estimate a model.
  static size_t MinNumSamples() { return 2; }

  // Estimate the most probable solution of the P3P problem from a set of
  // three 2D-3D point correspondences.
  //
  // @param points2D   Normalized 2D image points as 3x2 matrix.
  // @param points3D   3D world points as 3x3 matrix.
  //
  // @return           Most probable pose as length-1 vector of a 3x4 matrix.
  static std::vector<M_t> Estimate(const std::vector<X_t>& points2D,
                                   const std::vector<Y_t>& points3D);
  // Calculate the squared reprojection error given a set of 2D-3D point
  // correspondences and a projection matrix.
  //
  // @param points2D     Normalized 2D image points as Nx2 matrix.
  // @param points3D     3D world points as Nx3 matrix.
  // @param proj_matrix  3x4 projection matrix.
  // @param residuals    Output vector of residuals.
  static void Residuals(const std::vector<X_t>& points2D,
                        const std::vector<Y_t>& points3D,
                        const M_t& proj_matrix, std::vector<double>* residuals);
};

/// points2D is the worldpoints
std::vector<P2PEstimator::M_t> P2PEstimator::Estimate(
    const std::vector<P2PEstimator::X_t>& points2D, const std::vector<P2PEstimator::Y_t>& points3D)
{
    CHECK_EQ(points2D.size(), 2);
    CHECK_EQ(points3D.size(), 2);

    Eigen::Vector3d p1(points2D[0](0), points2D[0](1), 1.0);
    Eigen::Vector3d p2(points2D[1](0), points2D[1](1), 1.0);

    Eigen::Vector3d c1 = p1 / p1.norm();
    Eigen::Vector3d c2 = p2 / p2.norm();
    if(acos(c1.dot(c2)) * 180 / 3.141592653 < 1.5)
    {
        return {};
    }

    Eigen::MatrixXd A = Eigen::MatrixXd::Zero(4, 3);
    A(0, 0) = 1.0;
    A(1, 1) = 1.0;
    A(2, 0) = 1.0;
    A(3, 1) = 1.0;
    A(0, 2) = -1.0 * p1(0), A(1, 2) = -1.0 * p1(1);
    A(2, 2) = -1.0 * p2(0), A(3, 2) = -1.0 * p2(1);

    Eigen::VectorXd B(4, 1);
    Eigen::Vector3d X1 = points3D[0];
    Eigen::Vector3d X2 = points3D[1];
    B(0) = -X1(0) + X1(2) * p1(0);
    B(1) = -X1(1) + X1(2) * p1(1);
    B(2) = -X2(0) + X2(2) * p2(0);
    B(3) = -X2(1) + X2(2) * p2(1);

    Eigen::VectorXd solution(3, 1);
    solution = (A.transpose() * A).inverse() * A.transpose() * B;

    std::vector<M_t> models;
    M_t solutionM;
    Eigen::Matrix3d Rprior =  Eigen::Matrix3d::Identity();
    solutionM.leftCols<3>() = Rprior;
    solutionM.rightCols<1>() = solution; // T
    models.push_back(solutionM);

    return models;
}

void P2PEstimator::Residuals(const std::vector<X_t>& points2D,
                             const std::vector<Y_t>& points3D,
                             const M_t& proj_matrix,
                             std::vector<double>* residuals)
{
  ComputeSquaredReprojectionError(points2D, points3D, proj_matrix, residuals);
}

}  // namespace colmap

#endif  // COLMAP_SRC_ESTIMATORS_P2P_H_
